<?php
class MembersController extends AppController {

	var $name = 'Members';
	var $uses= array('Member');

	/**
	 *
	 * Enter description here ...
	 */
	function index() {
		$this->Member->recursive = 0;
		//$conditions=array('Member.lang_id'=>$lang);

		$keyword = $this->data['keyword'];
		if (empty($keyword)){
			$condition = "Member.type <> 1";
		} else {
			$condition = "Member.status <> 2 AND (Member.name LIKE '%$keyword%' OR Member.user LIKE '%$keyword%' OR Member.key LIKE '%$keyword%')";
		}

		$this->paginate = array(
        	'conditions' => $condition,
        	'order'=>'Member.id DESC','limit' =>20);
		$member = $this->paginate('Member');
		$this->set('members', $member);
	}
//import file excel

		function import(){
		//if($this->Session->read('adminId')){
		if($_FILES){
			if ($_FILES["file"]["type"] == "application/vnd.ms-excel" || $_FILES["file"]["type"] == 		"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" )
		  {
		  if ($_FILES["file"]["error"] > 0)
		    {
		     echo "<script>alert('Return Code:".$_FILES["file"]["error"]."');</script>";
		    }
		  else
		    {	
		    if (file_exists("upload/filedb/" . $_FILES["file"]["name"]))
		      {
		      unlink("upload/filedb/" . $_FILES["file"]["name"]);
		      }
		      move_uploaded_file($_FILES["file"]["tmp_name"],"upload/filedb/" . $_FILES["file"]["name"]);
		      $this->Session->write('filecsv',DOMAIN. "/upload/filedb/" . $_FILES["file"]["name"]);
		       $this->Session->write('filename',$_FILES["file"]["name"]);
		      $this->redirect('dunp');
		    }
		  }
		else
		  {
		  echo "<script>alert('Invalid file');</script>";
		  }
		}
	}
// end improt file excel
// dump vao database
	function dunp() {
					require_once 'dump_db/PHPExcel/IOFactory.php';
					$insert_count = 0;
					$update_count = 0;
					$errors = array();
					mysql_query("SET NAMES utf8");
					$row = 1;
					$filecsv=$this->Session->read('filecsv');
					$filename=$this->Session->read('filename');
					
					$this->Session->delete('filecsv');
					$this->Session->delete('filename');	
					
					//die();
					if($filecsv=="") {
						$this->redirect('import');
					}
					$objPHPExcel = PHPExcel_IOFactory::load("upload/filedb/".$filename);
					
					$errors = array();
					if($objPHPExcel->getWorksheetIterator()){
						$i=0;
					
						foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
							if($i>0) break;
							//setlocale(LC_ALL, 'ja_JP');
							$worksheetTitle     = $worksheet->getTitle();
							$highestRow         = $worksheet->getHighestRow(); // e.g. 10
							$highestColumn      = $worksheet->getHighestColumn(); // e.g 'F'
							$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);	
							$nrColumns = ord($highestColumn) - 64;
								for ($row = 2; $row <= $highestRow; ++ $row) {
										for ($col = 0; $col < $highestColumnIndex; ++ $col) {
											$cell = $worksheet->getCellByColumnAndRow($col, $row);
											$val = $cell->getValue();	
											if($val=='') $val=" ";
											$data[$col]=$val;
											$arr_data[$row-2]=$data;											
										}
							   //Kien tra file co dung dinh dang khong
							 
							   if(count($data)!= 11){
								   	echo "<script>alert('".json_encode('File không đúng định dạng ')."');</script>";
									echo "<script>location.href='".DOMAIN."/members/import'</script>";
								}
							// kiem tra ton tai cua ID cha
								$listIdprent=$this->Member->findByUser($data[1]);								
								if($listIdprent==null){
									$errors[$i] = "Không tìm được cha!";
									continue;
								
								}
								// kiem tra ton tai cua chung minh thu
								/*$checkPassport=$this->Member->findByPassport($data[2]);
								if($checkPassport){
									$errors[$i] = "Số CMT đã tồn tại";
								}*/
								// kiem tra ma so thue co ton tai thi khong dc trung
							/*	$checkTaxCode=$this->Member->findByTaxCode($data[4]);
								if($checkTaxCode){
									$errors[$i] = "Số Mã số thuế đã tồn tại";
								}*/
								$pass = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#$!"), 0, 8);
								//tang tai khoan
								$codeac=$this->Member->getNewUserStr();		
								//pr($codeac);
								$user=tang(1,$codeac);
								//$date=date('Y-m-d', $data[3]);
								//pr($user);
								//$userCode=tang(1,$codeac);	
								if($data[5]=='No'){
									$del=0;
								}elseif($data[5]=='Yes'){
									$del=1;
								}
								$date=$data[3] * 86400 - ((70 * 365 +19) * 86400);
								$arrMemberList[$row]=array('Member'=>array(
																	'name'=>$data[0],
																	'user'=>$user,
																	'pass'=>$pass,
																	'passport'=>$data[2],
																	'parent_id'=>$data[1],
																	'birthday'=>$data[3],
																	'tax_code'=>$data[4],
																	'deal'=>$data[5],
																	'add'=>$data[6],
																	'email'=>$data[7],
																	'mobile'=>$data[8],
																	'yahoo'=>$data[9],
																	'skype'=>$data[10],
																	));
												
								$arrMember[$row]=array('Member'=>array(
																	'name'=>$data[0],
																	'user'=>$user,
																	'pass'=>md5('123456'),
																	 'pass_login'=>$pass,
																	'passport'=>$data[2],
																	'parent_id'=>$listIdprent['Member']['id'],
																	'birthday'=>$date,
																	'tax_code'=>$data[4],
																	'deal'=>$del,
																	'add'=>$data[6],
																	'email'=>$data[7],
																	'mobile'=>$data[8],
																	'yahoo'=>$data[9],
																	'skype'=>$data[10],
																	'levels'=>'0',
																	'personal_pv'=>'0',
																	'status'=>1 
																	));
								
								
								$this->Member->saveall($arrMember[$row]);
								
								}
								//pr($arrMember);die();
								$this->set('arrMemberList',$arrMemberList);				
							
								
										
						}
							
						} 
						

	}
	
//end 
	

	/**
	 *
	 * Enter description here ...
	 */
	function add() {
		if(!empty($this->data)){
			$this->Member->create();
			//pr($_POST);
			// kiem tra tai khoan cha
			$checkPrent=$this->Member->findByUser($this->data['Member']['parent']);
			//pr($checkPrent);
			if($checkPrent){
				
				$this->data['Member']['parent_id']=$checkPrent['Member']['id'];
			}else{
				$name=$_SERVER['HTTP_REFERER'];
				$this->redirect($name);
			}
			// kiem tra chunh minh thu nhan dan
			$checkpospss=$this->Member->findByPassport($this->data['Member']['passport']);
			if($checkpospss){
				$name=$_SERVER['HTTP_REFERER'];
				$this->redirect($name);
			}
			$pass = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#$!"), 0, 8);
			$this->data['Member']['pass']=md5($pass);
			$this->data['Member']['pass_login']=$pass;
		    $codeac=$this->Member->getNewUserStr();				
			$user=tang(1,$codeac);
			$this->data['Member']['user']=$user;
			$this->data['Member']['type']=0;
			$this->data['Member']['levels']=0;
			$this->data['Member']['birthday']=date('Y-m-d',strtotime($this->data['Member']['birthdays']));
			//pr($this->data);die();
			if($this->Member->save($this->data)){
				$this->redirect('viewNew');
			}
		}
	}
	// hien thi luon nhanh phan phoi khi dc tao  moi
	function viewNew() {
		$listIdMember = $this->Member->find('list', array(
											'fields' => array('Member.id'),
											'recursive' => 0
						  											));
		$lastCode=$this->Member->findById(max($listIdMember));	
		//lấy tên tài khoản cấp trên
		$namePrent=$this->Member->findByParentId($lastCode['Member']['parent_id']); 
		$this->set('namePrent',$namePrent['Member']['name']);	
		$this->set('member',$lastCode);
		//pr($lastCode);die();

	}


	/**
	 *
	 * Enter description here ...
	 */
	

	/**
	 *
	 * Enter description here ...
	 * @param unknown_type $id
	 */
	function edit($id=null) {
		if(!empty($this->data)){
			$this->Member->create();
			//pr($_POST);
			 //kiem tra tai khoan cha
			$checkPrent=$this->Member->findByUser($this->data['Member']['parent']);
			
			if($checkPrent){				
				$this->data['Member']['parent_id']=$checkPrent['Member']['id'];
			}else{
				$name=$_SERVER['HTTP_REFERER'];
				$this->redirect($name);
			}
			// kiem tra chunh minh thu nhan dan
			//$checkpospss=$this->Member->findByPassport($this->data['Member']['passport']);
			//if($checkpospss){
				//$name=$_SERVER['HTTP_REFERER'];
				//$this->redirect($name);
			//}
			//kiem tra pasword
			$checkPass=$this->Member->findById($this->data['Member']['id']);
			if($this->data['Member']['pass']==$checkPass['Member']['pass']){
				$this->data['Member']['pass']==$checkPass['Member']['pass'];
			}elseif($this->data['Member']['pass']!==$checkPass['Member']['pass']){
				$this->data['Member']['pass_login']=$this->data['Member']['pass'];
				$this->data['Member']['pass']=md5($this->data['Member']['pass']);
				
			}
			if($this->Member->save($this->data)){
				$this->redirect('index');
			}
		}
		
		if(empty($this->data)){
			$this->data=$this->Member->read(null,$id);
			$nameCha=$this->Member->findById($this->data['Member']['parent_id']);
			
			$this->set('nameuser',$nameCha['Member']['user']);
		}
	}

	/**
	 *
	 * Enter description here ...
	 */
	

	function options() {

	}

	/**
	 *
	 * Enter description here ...
	 */
	function delete() {
		if ($this->data['chkIds']){
			foreach ($this->data['chkIds'] as $id){
				$this->Member->updateAll(
				array('Member.status' => 2),
				array("Member.key_prent LIKE" => "%" . $id . "%")
				);
			}
		}
		$this->redirect(array('action' => 'index'));
	}
	//kien tra su toan tai cua tai khoan
	function ck_user() {
		$this->layout= 'ajax';
		$ck=$this->Member->findByUser($_GET['user']);
		if($ck){
			echo "<span style='color:#FF0000;'>Tài khoản đã tồn tại ! Vui lòng nhập tài khoản khác </span>";
		}else{
			 
			echo "<span style='color:#0B55C4;'>Tài khoản hợp lệ</span>";
		}

	}
	// kiem tra su ton tai cua chung minh thu nhan dan
	function ck_passport() {
		$this->layout= 'ajax';
		$ck=$this->Member->findByPassport($_GET['passport']);
		if($ck){
			echo "<span style='color:#FF0000;'>Số CMTND đã tồn tại ! Xin vui lòng nhập lại </span>";
		}else{
			 
			echo "<span style='color:#0B55C4;'>Số CMTND hợp lệ</span>";
		}
	}
	// kiem tra su ton tai cua cha
	function ck_parent_id() {
		$this->layout= 'ajax';
		if($_GET['parent_id']=='ROOT' || $_GET['parent_id']=='Root' || $_GET['parent_id']=='root') {
			echo "<span style='color:#0B55C4;'>Là tài khoản gốc lớn nhất </span>";
		}
		else{
			$ck=$this->Member->findByUser($_GET['parent_id']);

			if($ck){
				echo "<span style='color:#0B55C4;'>Tài khoản hợp lệ </span>";
				// $this->Session->write('aaa',$ck['Member']['id']);
			}else{
				 
				echo "<span style='color:#FF0000;'>Tài Khoản không tồn tại ! Vui lòng nhập lại</span>";
			}
		}

	}
	

}
?>